﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Text;

namespace SimpleBlog.Mvc
{
    public class XmlResult : ActionResult
    {
        // Properties
        public XDocument Data { get; set; }
        public bool Rss { get; set; }

        public XmlResult(XDocument data, bool rss = false)
        {
            Data = data;
            Rss = rss;
        }

        public XmlResult(string data, bool rss = false)
        {
            Data = XDocument.Parse(data);
            Rss = rss;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(Data.Declaration.Encoding))
            {
                Data.Declaration.Encoding = Encoding.UTF8.WebName; //Default encoding
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ClearContent();

            response.ContentType = Rss ? "application/rss+xml" : "application/xml";
            response.ContentEncoding = Encoding.GetEncoding(Data.Declaration.Encoding);

            if (Data != null)
            {
                Data.Save(response.OutputStream);
            }
            response.Flush();
            response.End();
        }

    }
}